package cn.lblbc.ziptool

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView

class ArchiveFileAdapter(
    private val onItemClick: (ArchiveFileItem) -> Unit,
    private val onItemLongClick: ((ArchiveFileItem) -> Unit)? = null
) : RecyclerView.Adapter<ArchiveFileAdapter.ViewHolder>() {
    private val fileList = mutableListOf<ArchiveFileItem>()

    fun updateData(newData: List<ArchiveFileItem>) {
        fileList.clear()
        fileList.addAll(newData)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_archive_file, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val fileItem = fileList[position]
        val context = holder.itemView.context
        // 显示时去掉文件夹名称后面的斜线
        val displayName = if (fileItem.isDirectory && fileItem.name.endsWith("/")) {
            fileItem.name.dropLast(1)
        } else {
            fileItem.name
        }
        holder.fileNameTextView.text = displayName
        
        // 设置图标和颜色，区分不同类型的文件
        if (fileItem.isDirectory) {
            // 使用自定义的文件夹图标
            holder.fileIconImageView.setImageResource(R.drawable.folder_icon)
            // 取消颜色过滤，使用图标原有的颜色
            holder.fileIconImageView.clearColorFilter()
        } else if (isImageFile(fileItem.name)) {
            // 根据图片类型选择对应的图标
            val extension = fileItem.name.substringAfterLast('.', "").lowercase()
            when (extension) {
                "jpg" -> holder.fileIconImageView.setImageResource(R.drawable.jpg_file_icon)
                "jpeg" -> holder.fileIconImageView.setImageResource(R.drawable.jpeg_file_icon)
                "png" -> holder.fileIconImageView.setImageResource(R.drawable.png_file_icon)
                "gif" -> holder.fileIconImageView.setImageResource(R.drawable.gif_file_icon)
                else -> holder.fileIconImageView.setImageResource(android.R.drawable.ic_menu_gallery)
            }
            // 取消颜色过滤，使用图标原有的颜色
            holder.fileIconImageView.clearColorFilter()
        } else if (fileItem.isTextFile()) {
            // 根据文本类型选择对应的图标
            val extension = fileItem.name.substringAfterLast('.', "").lowercase()
            when (extension) {
                "html", "htm" -> holder.fileIconImageView.setImageResource(R.drawable.html_file_icon)
                else -> holder.fileIconImageView.setImageResource(R.drawable.txt_file_icon)
            }
            // 取消颜色过滤，使用图标原有的颜色
            holder.fileIconImageView.clearColorFilter()
        } else if (isAudioFile(fileItem.name)) {
            // 使用自定义的音频图标
            val extension = fileItem.name.substringAfterLast('.', "").lowercase()
            if (extension == "mp3") {
                holder.fileIconImageView.setImageResource(R.drawable.mp3_file_icon)
            } else {
                holder.fileIconImageView.setImageResource(android.R.drawable.ic_media_play)
            }
            // 取消颜色过滤，使用图标原有的颜色
            holder.fileIconImageView.clearColorFilter()
        } else if (isVideoFile(fileItem.name)) {
            // 使用Android默认的视频图标
            holder.fileIconImageView.setImageResource(android.R.drawable.ic_media_pause)
            holder.fileIconImageView.setColorFilter(ContextCompat.getColor(context, R.color.video_color))
        } else if (isArchiveFile(fileItem.name)) {
            // 根据压缩包类型选择对应的图标
            val extension = fileItem.name.substringAfterLast('.', "").lowercase()
            when (extension) {
                "zip" -> holder.fileIconImageView.setImageResource(R.drawable.zip_file_icon)
                "rar" -> holder.fileIconImageView.setImageResource(R.drawable.rar_file_icon)
                "7z" -> holder.fileIconImageView.setImageResource(R.drawable.sz_file_icon)
                "tar" -> holder.fileIconImageView.setImageResource(R.drawable.tar_file_icon)
                else -> holder.fileIconImageView.setImageResource(android.R.drawable.ic_menu_save)
            }
            // 取消颜色过滤，使用图标原有的颜色
            holder.fileIconImageView.clearColorFilter()
        } else if (isApkFile(fileItem.name)) {
            // 使用Android默认的APK图标
            holder.fileIconImageView.setImageResource(android.R.drawable.ic_menu_manage)
            holder.fileIconImageView.setColorFilter(ContextCompat.getColor(context, R.color.file_color))
        } else if (isLibraryFile(fileItem.name)) {
            // 库文件 (.so, .dll, .dylib 等)
            holder.fileIconImageView.setImageResource(android.R.drawable.ic_menu_preferences)
            holder.fileIconImageView.setColorFilter(ContextCompat.getColor(context, R.color.library_color))
        } else {
            // 其他类型的文件，尝试根据扩展名匹配自定义图标
            val extension = fileItem.name.substringAfterLast('.', "").lowercase()
            val iconResId = getIconResourceByExtension(extension)
            if (iconResId != null) {
                holder.fileIconImageView.setImageResource(iconResId)
                holder.fileIconImageView.clearColorFilter()
            } else {
                // 如果没有匹配的自定义图标，使用Android默认图标
                holder.fileIconImageView.setImageResource(android.R.drawable.ic_menu_view)
                holder.fileIconImageView.setColorFilter(ContextCompat.getColor(context, R.color.file_color))
            }
        }
        
        holder.itemView.setOnClickListener {
            onItemClick(fileItem)
        }
        
        // 只对非文件夹项目启用长按功能
        if (onItemLongClick != null && !fileItem.isDirectory) {
            holder.itemView.setOnLongClickListener {
                onItemLongClick(fileItem)
                true
            }
        } else {
            holder.itemView.setOnLongClickListener(null)
        }
    }

    override fun getItemCount(): Int = fileList.size

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val fileIconImageView: ImageView = itemView.findViewById(R.id.fileIconImageView)
        val fileNameTextView: TextView = itemView.findViewById(R.id.fileNameTextView)
    }
}

data class ArchiveFileItem(
    val name: String,
    val isDirectory: Boolean,
    val path: String,
    val fullPath: String = path
)

// 判断是否为文本文件的扩展函数
fun ArchiveFileItem.isTextFile(): Boolean {
    if (this.isDirectory) return false
    
    val textExtensions = setOf(
        "txt", "xml", "json", "csv", "md", "log", "ini", "conf", "properties", 
        "yaml", "yml", "sql", "html", "htm", "css", "js", "ts", "java", 
        "kt", "cpp", "c", "h", "hpp", "py", "php", "rb", "go", "rs", "swift",
        "kt", "kts", "gradle", "bat", "sh", "ps1", "proto", "graphql", "scss", 
        "sass", "less", "jsx", "tsx", "vue"
    )
    
    val extension = this.name.substringAfterLast('.', "").lowercase()
    return extension in textExtensions
}

fun isImageFile(fileName: String): Boolean {
    val imageExtensions = setOf("jpg", "jpeg", "png", "gif", "bmp", "webp")
    val extension = fileName.substringAfterLast(".", "").lowercase()
    return extension in imageExtensions
}

fun isAudioFile(fileName: String): Boolean {
    val audioExtensions = setOf("mp3", "wav", "ogg", "flac", "m4a", "aac")
    val extension = fileName.substringAfterLast(".", "").lowercase()
    return extension in audioExtensions
}

fun isVideoFile(fileName: String): Boolean {
    val videoExtensions = setOf("mp4", "mkv", "avi", "mov", "wmv", "flv")
    val extension = fileName.substringAfterLast(".", "").lowercase()
    return extension in videoExtensions
}

fun isArchiveFile(fileName: String): Boolean {
    val archiveExtensions = setOf("zip", "rar", "7z", "tar", "gz", "bz2")
    val extension = fileName.substringAfterLast(".", "").lowercase()
    return extension in archiveExtensions
}

fun isApkFile(fileName: String): Boolean {
    val extension = fileName.substringAfterLast(".", "").lowercase()
    return extension == "apk"
}

fun isLibraryFile(fileName: String): Boolean {
    val libraryExtensions = setOf("so", "dll", "dylib", "a", "lib")
    val extension = fileName.substringAfterLast(".", "").lowercase()
    return extension in libraryExtensions
}

// 根据文件扩展名获取对应的图标资源ID
fun getIconResourceByExtension(extension: String): Int? {
    return when (extension.lowercase()) {
        "pdf" -> R.drawable.pdf_file_icon
        "doc" -> R.drawable.doc_file_icon
        "docx" -> R.drawable.docx_file_icon
        "xls" -> R.drawable.xls_file_icon
        "xlsx" -> R.drawable.xlsx_file_icon
        "ppt" -> R.drawable.ppt_file_icon
        "svg" -> R.drawable.svg_file_icon
        "psd" -> R.drawable.psd_file_icon
        "wps" -> R.drawable.wps_file_icon
        else -> null
    }
}